<template>
  <div class="step-container">
    <div class="content-section">
      <!-- 标题区域 -->
      <div class="header-section">
        <h2 class="main-title">试题生成</h2>
        <p class="subtitle">基于知识图谱智能生成试题</p>
      </div>

      <!-- 出题规则部分 -->
      <div class="rules-section">
        <h3 class="section-title">
          <el-icon><SetUp /></el-icon>
          出题规则
        </h3>
        <div class="question-types">
          <div v-for="type in questionTypes" :key="type.value" class="question-type-item">
            <el-input-number 
              v-model="type.count" 
              :min="0" 
              :max="20"
              size="small"
              controls-position="right"
            />
            <span class="type-label">{{ type.label }}</span>
          </div>
        </div>
        
        <div class="difficulty-distribution">
          <h4>难度分布</h4>
          <div class="difficulty-sliders">
            <div class="difficulty-item">
              <span>简单</span>
              <el-slider v-model="difficulties.easy" :max="100" @change="adjustDifficulties('easy')" />
              <span class="percentage">{{ difficulties.easy }}%</span>
            </div>
            <div class="difficulty-item">
              <span>中等</span>
              <el-slider v-model="difficulties.medium" :max="100" @change="adjustDifficulties('medium')" />
              <span class="percentage">{{ difficulties.medium }}%</span>
            </div>
            <div class="difficulty-item">
              <span>困难</span>
              <el-slider v-model="difficulties.hard" :max="100" @change="adjustDifficulties('hard')" />
              <span class="percentage">{{ difficulties.hard }}%</span>
            </div>
          </div>
          <div class="difficulty-total" :class="{ 'error': totalDifficulty !== 100 }">
            总计: {{ totalDifficulty }}% {{ totalDifficulty !== 100 ? '(需等于100%)' : '' }}
          </div>
        </div>
      </div>

      <!-- 试题生成进度区域 -->
      <div v-if="generating" class="generation-progress">
        <div class="progress-header">
          <h3 class="section-title">
            <el-icon><Loading /></el-icon>
            生成进度
          </h3>
          <div class="progress-stats">
            已生成: <span class="progress-value">{{ generatedCount }}</span> / {{ totalExpectedQuestions }} 题
          </div>
        </div>
        
        <el-progress
          :percentage="processingPercentage" 
          :status="processingStatus"
          :stroke-width="15"
          :format="progressFormat"
          striped
          :striped-flow="processingStatus !== 'exception'"
        />
        
        <div class="progress-message">
          <p>{{ processingMessage }}</p>
          <p v-if="estimatedTimeLeft > 0" class="time-estimate">
            预计剩余时间: {{ formattedTimeLeft }}
          </p>
        </div>
      </div>

      <!-- 题目预览部分 -->
      <div class="preview-section" :class="{ 'with-progress': generating }">
        <div class="preview-header">
          <h3 class="section-title">
            <el-icon><Document /></el-icon>
            试题预览
          </h3>
          <div class="preview-stats" v-if="previewQuestions.length > 0">
            <el-tag type="success">{{ previewQuestions.length }}题</el-tag>
          </div>
        </div>
        
        <previewQuestion :previewQuestions="previewQuestions" v-if="previewQuestions.length > 0"/>
        <div v-else class="preview-placeholder">
          <el-empty description="暂无预览题目" />
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="action-buttons">
        <el-button 
          type="primary" 
          @click="handleGenerate" 
          :loading="generating"
          :disabled="!canGenerate"
        >
          <el-icon><DocumentAdd /></el-icon>
          {{ generating ? '生成中...' : '生成试题' }}
        </el-button>
        <el-button 
          type="success" 
          @click="handleComplete" 
          :disabled="!previewQuestions.length"
        >
          <el-icon><Check /></el-icon>
          保存试题
        </el-button>
      </div>
    </div>

    <!-- 添加选择学科和题库的弹窗 -->
    <el-dialog
      class="dialog"
      v-model="dialogVisible"
      title="选择学科和题库"
      width="30%"
      :before-close="handleClose"
    >
      <div class="dialog-content">
        <div class="select-item">
          <span class="label">选择学科:</span>
          <el-select v-model="selectedSubject" placeholder="请选择学科" @change="handleSubjectChange">
            <el-option
              v-for="item in subjects"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="select-item">
          <span class="label">选择题库:</span>
          <el-select v-model="selectedLibrary" placeholder="请选择题库">
            <el-option
              v-for="item in libraries"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="saving">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="GenerateQuestion">
import { ref, computed, watch, onMounted } from 'vue'
import { Check, SetUp, Document, DocumentAdd, Loading } from '@element-plus/icons-vue'
import { useActiveStepIndex } from '../../stores/counter'
import { useTextContent } from '../../stores/textContent'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { generateQuestions } from '../../api/ai'
import { getQuestions } from '../../api/question'
import { useQuestionIds } from '../../stores/counter'
import { getSubjects } from '../../api/subject'
import { getLibrariesBySubject } from '../../api/library'
import { saveQuestions } from '../../api/question'

const useStepIndex = useActiveStepIndex()
const textContent = useTextContent()  
const questionIds = useQuestionIds()

// 题型配置
const questionTypes = ref([
  { value: 'SINGLE_CHOICE', label: '单选题', count: 1 },
  { value: 'MULTIPLE_CHOICE', label: '多选题', count: 1 },
  { value: 'TRUE_FALSE', label: '判断题', count: 1 },
  { value: 'FILL_BLANK', label: '填空题', count: 0 },
  { value: 'SHORT_ANSWER', label: '简答题', count: 0 },
  { value: 'READING', label: '综合题', count: 0 }
])

// 难度分布
const difficulties = ref({
  easy: 30,
  medium: 40,
  hard: 30
})

// 总体难度分布
const totalDifficulty = computed(() => {
  return difficulties.value.easy + difficulties.value.medium + difficulties.value.hard
})

// 调整难度分布，保持总和为100%
const adjustDifficulties = (changedKey) => {
  const total = totalDifficulty.value
  if (total === 100) return

  const otherKeys = ['easy', 'medium', 'hard'].filter(k => k !== changedKey)
  
  // 如果总和不等于100，调整其他难度值
  if (total > 100) {
    // 计算需要减少的总量
    const excessAmount = total - 100
    
    // 按比例分配减少量到其他难度
    const totalOther = otherKeys.reduce((sum, key) => sum + difficulties.value[key], 0)
    if (totalOther > 0) {
      otherKeys.forEach(key => {
        const proportion = difficulties.value[key] / totalOther
        const reduction = Math.round(excessAmount * proportion)
        difficulties.value[key] = Math.max(0, difficulties.value[key] - reduction)
      })
    }
  } else if (total < 100) {
    // 计算需要增加的总量
    const deficitAmount = 100 - total
    
    // 按比例分配增加量到其他难度
    const totalOther = otherKeys.reduce((sum, key) => sum + difficulties.value[key], 0)
    if (totalOther > 0) {
      otherKeys.forEach(key => {
        const proportion = difficulties.value[key] / totalOther
        const addition = Math.round(deficitAmount * proportion)
        difficulties.value[key] += addition
      })
    } else {
      // 如果其他难度都为0，平均分配
      const addition = Math.floor(deficitAmount / otherKeys.length)
      otherKeys.forEach(key => {
        difficulties.value[key] += addition
      })
    }
  }
  
  // 由于舍入错误，可能总和仍不是100，调整第一个非零难度
  const finalTotal = Object.values(difficulties.value).reduce((sum, val) => sum + val, 0)
  if (finalTotal !== 100) {
    const diff = 100 - finalTotal
    for (const key of otherKeys) {
      if (difficulties.value[key] + diff >= 0) {
        difficulties.value[key] += diff
        break
      }
    }
  }
}

// 预览题目列表
const previewQuestions = ref([])
const generating = ref(false)
const processingPercentage = ref(0)
const processingStatus = ref('')
const processingMessage = ref('')
const generatedCount = ref(0)
const startTime = ref(0)
const estimatedTimeLeft = ref(0)
const formattedTimeLeft = computed(() => {
  if (estimatedTimeLeft.value <= 0) return '正在计算...'
  
  const minutes = Math.floor(estimatedTimeLeft.value / 60)
  const seconds = Math.floor(estimatedTimeLeft.value % 60)
  
  if (minutes > 0) {
    return `${minutes}分${seconds}秒`
  } else {
    return `${seconds}秒`
  }
})

// 保存相关状态
const dialogVisible = ref(false)
const subjects = ref([])
const libraries = ref([])
const selectedSubject = ref('')
const selectedLibrary = ref('')
const saving = ref(false)

// 计算总共需要生成的题目数量
const totalExpectedQuestions = computed(() => {
  return questionTypes.value.reduce((sum, type) => sum + type.count, 0)
})

// 检查是否可以生成题目
const canGenerate = computed(() => {
  const hasTypes = questionTypes.value.some(type => type.count > 0)
  const validDifficulty = totalDifficulty.value === 100
  const hasContent = textContent.textContent && textContent.textContent.trim().length > 0
  
  return hasTypes && validDifficulty && hasContent && !generating.value
})

// 进度条格式化
const progressFormat = (percentage) => {
  if (percentage === 100) return '完成'
  return `${percentage}%`
}

// 获取学科列表
const fetchSubjects = async () => {
  try {
    const userId = JSON.parse(localStorage.getItem('user')).id
    const res = await getSubjects(userId, 1, 100)
    subjects.value = res.data.list
  } catch (error) {
    ElMessage.error('获取学科列表失败')
  }
}

// 获取题库列表
const fetchLibraries = async (subjectId) => {
  try {
    const res = await getLibrariesBySubject(subjectId, 1, 100)
    libraries.value = res.data.list
  } catch (error) {
    ElMessage.error('获取题库列表失败')
  }
}

// 学科选择改变时获取对应的题库列表
const handleSubjectChange = async (value) => {
  selectedLibrary.value = ''
  if (value) {
    await fetchLibraries(value)
  } else {
    libraries.value = []
  }
}

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false
  selectedSubject.value = ''
  selectedLibrary.value = ''
  libraries.value = []
}

// 确认选择
const handleConfirm = async () => {
  if (!selectedSubject.value || !selectedLibrary.value) {
    ElMessage.warning('请选择学科和题库')
    return
  }
  
  try {
    saving.value = true
    // 保存题目到选中的题库
    const result = await saveQuestions(selectedLibrary.value, previewQuestions.value)
    saving.value = false
    
    if (result && result.code === 200) {
      ElMessage.success({
        message: '试题保存成功',
        duration: 3000
      })
      dialogVisible.value = false
      
      // 显示保存结果提示
      ElMessageBox.alert(
        `已成功保存 ${previewQuestions.value.length} 道试题到题库`,
        '保存成功',
        {
          confirmButtonText: '确定',
          type: 'success',
          callback: () => {
            // 可选：清空当前生成的题目，准备下一轮生成
            if (previewQuestions.value.length > 0) {
              ElMessageBox.confirm(
                '是否清空当前生成的题目，准备下一轮生成？',
                '提示',
                {
                  confirmButtonText: '清空',
                  cancelButtonText: '保留',
                  type: 'info'
                }
              ).then(() => {
                previewQuestions.value = []
                processingPercentage.value = 0
                processingMessage.value = ''
                generatedCount.value = 0
              }).catch(() => {
                // 用户选择保留
              })
            }
          }
        }
      )
    } else {
      ElMessage.error('保存失败: ' + (result?.message || '未知错误'))
    }
  } catch (error) {
    saving.value = false
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  }
}

// 生成试题
const handleGenerate = async () => {
  // 验证题目数量
  const totalQuestions = questionTypes.value.reduce((sum, type) => sum + type.count, 0)
  if (totalQuestions === 0) {
    ElMessage.warning('请至少选择一道题目')
    return
  }

  // 验证难度分布
  if (totalDifficulty.value !== 100) {
    ElMessage.warning('难度分布总和必须为100%')
    return
  }

  // 检查文本内容
  if (!textContent.textContent || textContent.textContent.trim().length === 0) {
    ElMessage.warning('生成内容为空，请先提供知识点文本')
    return
  }

  // 确认对话框
  ElMessageBox.confirm(
    `即将生成 ${totalQuestions} 道试题，可能需要几分钟时间，是否继续？`,
    '开始生成',
    {
      confirmButtonText: '继续',
      cancelButtonText: '取消',
      type: 'info'
    }
  ).then(() => {
    startGenerating()
  }).catch(() => {
    // 用户取消操作
  })
}

// 开始生成试题
const startGenerating = async () => {
  generating.value = true
  processingPercentage.value = 0
  processingStatus.value = ''
  processingMessage.value = '正在准备生成试题...'
  startTime.value = Date.now()
  estimatedTimeLeft.value = 0
  
  // 如果再次生成，清空之前的预览题目
  if (previewQuestions.value.length > 0) {
    previewQuestions.value = []
  }
  generatedCount.value = 0

  try {
    const model = localStorage.getItem('aiModel') || 'deepseek'
    const baseUrl = import.meta.env.VITE_API_BASE_URL || ''
    
    // 创建 POST 请求的配置
    const headers = new Headers({
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
    })
    
    // 构建请求体
    const body = JSON.stringify({
      questionTypes: questionTypes.value.filter(type => type.count > 0),
      message: textContent.textContent,
      easy: difficulties.value.easy,
      medium: difficulties.value.medium,
      hard: difficulties.value.hard
    })
    
    // 使用 fetch API 发送请求
    const controller = new AbortController()
    const timeoutId = setTimeout(() => controller.abort(), 900000) // 15分钟超时
    
    try {
      const response = await fetch(`${baseUrl}/ai/generate/stream?provider=${model}&chatSession=chatSession`, {
        method: 'POST',
        headers: headers,
        body: body,
        signal: controller.signal
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      const reader = response.body.getReader()
      const decoder = new TextDecoder()
      
      // 用于跟踪活跃状态的变量
      let lastActivityTime = Date.now()
      const heartbeatChecker = setInterval(() => {
        const inactiveTime = Date.now() - lastActivityTime
        // 如果超过3分钟没有活动，可能连接有问题
        if (inactiveTime > 180000) {
          console.warn('连接长时间无活动，可能已断开')
          clearInterval(heartbeatChecker)
          controller.abort()
          handleGenerationError('生成题目超时，请重试')
        }
        
        // 更新预计剩余时间
        updateEstimatedTime()
      }, 10000) // 每10秒检查一次
      
      let buffer = ''
      let currentEvent = null
      processingPercentage.value = 5
      processingMessage.value = '正在连接服务器并开始生成...'
      
      try {
        while (true) {
          const { done, value } = await reader.read()
          
          // 更新活跃时间
          lastActivityTime = Date.now()
          
          if (done) {
            clearInterval(heartbeatChecker)
            break
          }
          
          buffer += decoder.decode(value, { stream: true })
          const lines = buffer.split('\n')
          buffer = lines.pop() || ''
          
          for (const line of lines) {
            if (line.startsWith('event:')) {
              currentEvent = line.slice(6).trim()        
            }
            
            if (line.startsWith('data:')) {
              const data = line.slice(5).trim()
              
              // 处理心跳数据，重置活跃计时器
              if (data === 'processing') {
                lastActivityTime = Date.now()
                continue
              }
              
              if (currentEvent && data) {
                try {
                  switch (currentEvent) {
                    case 'generating':
                      processingMessage.value = data
                      processingPercentage.value = 10
                      break
                      
                    case 'progress':
                      const progressValue = parseFloat(data)
                      if (!isNaN(progressValue)) {
                        // 将进度值限制在10-95之间，留出开始和结束的余量
                        processingPercentage.value = Math.min(95, Math.max(10, progressValue))
                      }
                      updateEstimatedTime()
                      break
                      
                    case 'heartbeat':
                      lastActivityTime = Date.now()
                      break
                      
                    case 'questionId':
                      const id = parseInt(data)
                      if (!isNaN(id)) {
                        try {
                          const result = await getQuestions(id.toString())
                          if (result.code === 200 && result.data && result.data.length > 0) {
                            const newQuestion = result.data[0]
                            // 检查是否已存在相同ID的题目
                            const existingIndex = previewQuestions.value.findIndex(q => q.id === newQuestion.id)
                            if (existingIndex === -1) {
                              previewQuestions.value = [...previewQuestions.value, newQuestion]
                              generatedCount.value++
                              
                              // 更新进度消息
                              processingMessage.value = `已生成 ${generatedCount.value} 道题目，正在继续...`
                              
                              // 只在较大间隔时显示消息，避免消息过多
                              if (generatedCount.value % 3 === 0 || generatedCount.value === 1) {
                                ElMessage({
                                  message: `已生成 ${generatedCount.value} 道题目`,
                                  type: 'success',
                                  duration: 2000
                                })
                              }
                              
                              // 更新进度条
                              const progressRatio = Math.min(0.95, generatedCount.value / totalExpectedQuestions.value)
                              processingPercentage.value = Math.max(processingPercentage.value, progressRatio * 100)
                            }
                          }
                        } catch (err) {
                          console.error('获取题目详情失败:', err)
                        }
                      }
                      break
                      
                    case 'questions':
                      console.log('收到所有题目IDs')
                      try {
                        const ids = JSON.parse(data)
                        if (Array.isArray(ids)) {
                          questionIds.setQuestionIds(ids)
                          
                          // 检查是否有遗漏的题目
                          const missingIds = ids.filter(id => !previewQuestions.value.some(q => q.id === id))
                          if (missingIds.length > 0) {
                            processingMessage.value = `正在获取剩余 ${missingIds.length} 道题目...`
                            
                            // 使用 Promise.all 并行获取所有遗漏的题目
                            const missingPromises = missingIds.map(id => getQuestions(id.toString()))
                            try {
                              const missingResults = await Promise.all(missingPromises)
                              for (const result of missingResults) {
                                if (result.code === 200 && result.data && result.data.length > 0) {
                                  previewQuestions.value = [...previewQuestions.value, result.data[0]]
                                  generatedCount.value++
                                }
                              }
                            } catch (error) {
                              console.error('获取遗漏题目出错:', error)
                            }
                          }
                        }
                      } catch (err) {
                        console.error('处理题目IDs失败:', err)
                      }
                      break
                      
                    case 'complete':
                      // 生成完成
                      processingPercentage.value = 100
                      processingStatus.value = 'success'
                      processingMessage.value = `成功生成 ${generatedCount.value} 道题目`
                      
                      // 通知用户完成
                      ElMessage({
                        message: `题目生成完成，共生成 ${generatedCount.value} 道题目`,
                        type: 'success',
                        duration: 5000,
                        showClose: true
                      })
                      
                      // 清理定时器
                      clearInterval(heartbeatChecker)
                      generating.value = false
                      estimatedTimeLeft.value = 0
                      break
                      
                    case 'error':
                      handleGenerationError(data)
                      clearInterval(heartbeatChecker)
                      break
                  }
                } catch (err) {
                  console.error('处理事件数据失败:', err)
                }
              }
            }
          }
        }
      } catch (error) {
        // 处理读取流过程中的错误
        clearInterval(heartbeatChecker)
        if (error.name === 'AbortError') {
          handleGenerationError('请求被中止，可能是因为连接超时')
        } else {
          handleGenerationError(`读取响应出错: ${error.message}`)
        }
      } finally {
        clearTimeout(timeoutId)
      }
    } catch (fetchError) {
      // 处理fetch API本身的错误
      clearTimeout(timeoutId)
      if (fetchError.name === 'AbortError') {
        handleGenerationError('请求超时，生成题目失败')
      } else {
        handleGenerationError(`请求失败: ${fetchError.message}`)
      }
    }
  } catch (error) {
    handleGenerationError(`试题生成失败: ${error.message}`)
  }
}

// 更新预计剩余时间
const updateEstimatedTime = () => {
  if (generatedCount.value <= 0 || processingPercentage.value >= 100) {
    estimatedTimeLeft.value = 0
    return
  }
  
  const elapsedTime = (Date.now() - startTime.value) / 1000
  const progressRatio = generatedCount.value / totalExpectedQuestions.value
  
  if (progressRatio > 0) {
    const totalEstimatedTime = elapsedTime / progressRatio
    estimatedTimeLeft.value = Math.max(0, totalEstimatedTime - elapsedTime)
  }
}

// 错误处理函数
const handleGenerationError = (message) => {
  generating.value = false
  processingStatus.value = 'exception'
  processingMessage.value = `生成失败: ${message}`
  ElMessage.error(`生成试题失败: ${message}`)
}

// 保存试题
const handleComplete = () => {
  if (previewQuestions.value.length === 0) {
    ElMessage.warning('请先生成试题')
    return
  }
  // 显示选择弹窗
  dialogVisible.value = true
  // 获取学科列表
  fetchSubjects()
}

// 组件挂载时检查文本内容
onMounted(() => {
  // 如果没有文本内容，显示提示
  if (!textContent.textContent || textContent.textContent.trim().length === 0) {
    ElMessage.warning('请先在知识图谱页面选择章节内容')
  }
})
</script>

<style scoped>
.step-container {
  /* background-color: #f5f7fa; */
  min-height: 100vh;
}

.content-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  /* max-width: 1200px; */
  margin: 0 auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.header-section {
  text-align: center;
  margin-bottom: 32px;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.subtitle {
  margin-top: 8px;
  font-size: 16px;
  color: #909399;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-bottom: 16px;
}

.section-title .el-icon {
  margin-right: 8px;
  font-size: 20px;
  color: #409EFF;
}

.rules-section {
  margin-bottom: 24px;
  padding: 20px;
  /* background: #f8f9fa; */
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.rules-section h3,
.preview-section h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 18px;
  color: #303133;
}

.question-types {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.question-type-item {
  display: flex;
  align-items: center;
  gap: 12px;
  background: white;
  padding: 8px 12px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.type-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.difficulty-distribution {
  margin-top: 24px;
  background: white;
  padding: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.difficulty-distribution h4 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 16px;
  color: #333;
}

.difficulty-sliders {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.difficulty-item {
  display: flex;
  align-items: center;
  gap: 16px;
}

.difficulty-item span:first-child {
  width: 40px;
  font-size: 14px;
  color: #606266;
}

.difficulty-item .el-slider {
  flex: 1;
}

.percentage {
  min-width: 45px;
  text-align: right;
  color: #409EFF;
  font-weight: 500;
}

.difficulty-total {
  margin-top: 16px;
  text-align: right;
  font-size: 14px;
  color: #606266;
  padding-top: 12px;
  border-top: 1px dashed #ebeef5;
}

.difficulty-total.error {
  color: #f56c6c;
  font-weight: bold;
}

.preview-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  border: 1px solid #ebeef5;
}

.preview-section.with-progress {
  border-top: none;
  border-radius: 0 0 8px 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.preview-stats {
  display: flex;
  gap: 8px;
}

.question-preview {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.question-card {
  margin-bottom: 16px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.question-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  gap: 12px;
}

.question-index {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.question-type-tag,
.difficulty-tag {
  margin-right: 8px;
}

.question-content {
  margin-bottom: 16px;
}

.question-stem {
  font-size: 15px;
  line-height: 1.6;
  color: #333;
  margin-bottom: 16px;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  display: flex;
  gap: 8px;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.option-id {
  font-weight: bold;
  color: #409EFF;
}

.preview-placeholder {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 24px;
}

.action-buttons .el-button {
  min-width: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.dialog-content {
  padding: 20px 0;
}

.select-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.select-item .label {
  width: 80px;
  margin-right: 10px;
}

.select-item .el-select {
  width: 100%;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
  .content-section {
    padding: 16px;
  }
  
  .question-types {
    grid-template-columns: 1fr;
  }

  .difficulty-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .difficulty-item .el-slider {
    width: 100%;
    margin: 0;
  }

  .percentage {
    align-self: flex-end;
  }
  
  .progress-message {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .action-buttons .el-button {
    width: 100%;
  }
}

.generation-progress {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 24px;
  border: 1px solid #ebeef5;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.progress-stats {
  font-size: 14px;
  color: #606266;
}

.progress-value {
  font-weight: bold;
  color: #409EFF;
}

.progress-message {
  margin-top: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.time-estimate {
  font-style: italic;
  color: #909399;
}
</style>